package com.zs.grain.ui

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.content.res.Configuration
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.drawable.BitmapDrawable
import android.net.ConnectivityManager
import android.net.NetworkInfo
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.PersistableBundle
import android.provider.MediaStore
import android.text.InputType
import android.util.Log
import android.view.MotionEvent
import android.view.View
import android.webkit.*
import android.widget.MediaController
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.jeremyliao.liveeventbus.LiveEventBus
import com.xnkj1688.semplibrary.dialog.InputNumberDialog
import com.xnkj1688.semplibrary.mvvm.BaseMvvmActivity
import com.zs.grain.ARouterPath
import com.zs.grain.R
import com.zs.grain.databinding.ActivityMainBinding
import com.zs.grain.databinding.FragmentAdsBinding
import kotlinx.android.synthetic.main.activity_main_webview.*
import java.io.File
import java.io.IOException
import java.util.*
import kotlin.concurrent.schedule

@Route(path = ARouterPath.MainActivity)
class MainActivity : BaseMvvmActivity<ActivityMainBinding, MainViewModel>() {

//    private lateinit var mWebView: WebView
//    internal var URL = "https://cn.bing.com/"//"https://www.infixsoft.com/"//
//    private lateinit var mContext: Context
    override val layoutId = R.layout.activity_main//_webview

    override fun initViewModel(binding: ActivityMainBinding) {
        //if (!mViewModel.mDataService.isFirstStart) throw Exception("应用重启")

        binding.vm = this.mViewModel
        binding.view = this


//        val webview = WebView(this)
//        setContentView(webview)
//        webview.settings.javaScriptEnabled = true
//        webview.setWebViewClient(WebViewClient())
//        webview.loadUrl("https://www.baidu.com")
        //binding.view.

//        val webSettings:WebSettings = this.activity_main_wv.getSettings()
//        webSettings.javaScriptEnabled = true
//        this.activity_main_wv.setWebViewClient(MyWebViewClient())
//        this.activity_main_wv.loadUrl("https://cn.bing.com/")



//        LiveEventBus.get().with("videoViewMainCurrentPosition", Int::class.java)
//            .observeStickyForever() {
//                //binding.videoView.//样式修改
//                binding.videoView.seekTo(it)//.setProgress(it)//.subscribe({}, {})
//            }

        LiveEventBus.get("RefreshVideoView", Boolean::class.java)
            .observe(this, Observer {
                //refreshVideoViewLayout(binding,it)//false时显示videoView
                if(it) {
                    binding.guideline1.setGuidelineBegin(1920)
                    binding.guideline2.setGuidelineBegin(1920)
                }else {binding.guideline2.setGuidelineBegin(685)
                    binding.guideline1.setGuidelineBegin(608)
                    //binding.videoView.seekTo(20000)
                }
            })

        LiveEventBus.get("AutoRestart", Boolean::class.java)
            .observe(this, Observer {
                mViewModel.insertLog("Operation:自动重启")
            })

        LiveEventBus.get("DeviceService.SwipeCard", String::class.java)
            .observe(this, Observer {//it.toString()   java.lang.Integer.toHexString(
                var auth = mViewModel.mDataService.cardDatas.get(it.toString())
                if (auth != null && auth != "") {
                        this.mViewModel.enterMaintenance(
                            it.toString(),
                            auth
                        )
                }//it.toString()
                else Toast.makeText(this,"NFC卡不匹配:"+it.toString(),Toast.LENGTH_LONG).show()
            })
        LiveEventBus.get("SwitchUI", Bundle::class.java).observe(this, Observer {
            var ui = it.getString("UI")
            var TempType = it.getInt("TempType")
            var fb = it.getBoolean("finishProduct")
            when (ui) {
                "Temp" -> {
                    //mBinding.videoView.stopPlayback()
                    var fragment = ARouter.getInstance().build(ARouterPath.TempFragment)
                        .withInt("TempType", TempType)
                        .navigation() as Fragment
                    supportFragmentManager.beginTransaction()
                        .replace(R.id.container, fragment, "Temp")
                        .commit()
                }
                "Menus" -> {
                    LiveEventBus.get("ProductFinsh.checkTask").post(true)
                    if(fb){
                        Handler().postDelayed({
                            mViewModel.mDataService.insertLog("State:产品完成,延时2秒回首页")
                            var fragment = ARouter.getInstance().build(ARouterPath.MenusFragment)
                                .navigation() as Fragment
                            supportFragmentManager.beginTransaction()
                                .replace(R.id.container, fragment, "Menus")
                                .commit()
                        }, 2000)
                    }else {
                        var fragment = ARouter.getInstance().build(ARouterPath.MenusFragment)
                            .navigation() as Fragment
                        supportFragmentManager.beginTransaction()
                            .replace(R.id.container, fragment, "Menus")
                            .commit()
                    }
                }
                "Deploy" -> {
                    var fragment = ARouter.getInstance().build(ARouterPath.DeployFragment)
                        .withLong("MenuNo", it.getLong("MenuNo"))
                        .navigation() as Fragment
                    supportFragmentManager.beginTransaction()
                        .replace(R.id.container, fragment, "Deploy")
                        .commit()
                }
                "ScanQr" -> {
                    var fragment = ARouter.getInstance().build(ARouterPath.ScanQrFragment)
                        .withLong("OrderId", it.getLong("OrderId"))
                        .withLong("goodId", it.getLong("goodId"))
                        .withInt("sealIndex", it.getInt("sealIndex"))
                        .withInt("sugarIndex", it.getInt("sugarIndex"))
                        .navigation() as Fragment
                    supportFragmentManager.beginTransaction()
                        .replace(R.id.container, fragment, "ScanQr")
                        .commit()
                }
                "Waiting" -> {
                    var fragment = ARouter.getInstance().build(ARouterPath.WaitingFragment)
                        .withLong("OrderId", it.getLong("OrderId"))
                        .navigation() as Fragment
                    supportFragmentManager.beginTransaction()
                        .replace(R.id.container, fragment, "Waiting")
                        .commit()
                }
                "Finish" -> {
                    var fragment = ARouter.getInstance().build(ARouterPath.FinishFragment)
                        .withLong("OrderId", it.getLong("OrderId"))
                        .navigation() as Fragment
                    supportFragmentManager.beginTransaction()
                        .replace(R.id.container, fragment, "Finish")
                        .commit()
                }
            }
        })
    }

    var lock = java.lang.Object()
    override fun initAction() {
        super.initAction()
        mPasswordDialog = InputNumberDialog(this, R.style.Dialog)
        val media = MediaController(this)
        mBinding.videoView.setMediaController(media)
        media.visibility = View.GONE

        mViewModel.init()
    }
    //@SuppressLint("SetJavaScriptEnabled")//TODO:add to test webview
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Log.d(TAG, "onCreate")
//        mContext = this
//        mWebView = findViewById<View>(R.id.activity_main_wv) as WebView
//        requestWebView()
    }

    override fun onStart() {
        super.onStart()
        Log.d(TAG, "onStart")
    }

    override fun onConfigurationChanged(newConfig: Configuration) {
        super.onConfigurationChanged(newConfig)
        Log.d(TAG, "onConfigurationChanged" + newConfig.toString())
    }

    override fun onResume() {
        super.onResume()
        Log.d(TAG, "onResume")
        mViewModel.init()
    }

    override fun onPause() {
        super.onPause()
        Log.d(TAG, "onPause")
    }

    override fun onStop() {
        super.onStop()
        Log.d(TAG, "onStop")
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.d(TAG, "onDestroy")
    }

    override fun onRestart() {
        super.onRestart()
        Log.d(TAG, "onRestart")
    }

    override fun onSaveInstanceState(outState: Bundle?, outPersistentState: PersistableBundle?) {
        super.onSaveInstanceState(outState, outPersistentState)
        Log.d(TAG, "onSaveInstanceState")
    }

    override fun onRestoreInstanceState(savedInstanceState: Bundle?) {
        super.onRestoreInstanceState(savedInstanceState)
        Log.d(TAG, "onRestoreInstanceState")
    }

    override fun onLowMemory() {
        super.onLowMemory()
        Log.d(TAG, "onLowMemory")
    }

    override fun onTrimMemory(level: Int) {
        super.onTrimMemory(level)
        Log.d(TAG, "onTrimMemory:" + level)
    }

    //动态调整约束布局
    private fun refreshVideoViewLayout(binding:FragmentAdsBinding,isHide:Boolean){
        //if(isHide)
    }

    private fun play(fileName: String) {
        var path = fileName
        if (path.toLowerCase().endsWith(".mov")
            || path.toLowerCase().endsWith(".mkv")
            || path.toLowerCase().endsWith(".mp4")
            || path.toLowerCase().endsWith(".avi")
        ) {
            val uri = Uri.parse(path)

            mBinding.videoView.setVideoURI(uri)
//                    mBinding.videoView.setOnPreparedListener { mediaPlayer -> mediaPlayer.isLooping = true }
            mBinding.videoView.setOnErrorListener { mediaPlayer, i, i1 ->
                mViewModel.onVideoError(mediaPlayer, i, i1)
            }
            mBinding.videoView.setOnCompletionListener {
                mViewModel.onVideoCompletion()
            }
            mBinding.videoView.setBackground(null);
            mBinding.videoView.start()

            mBinding.videoView.requestFocus()
        } else {
            var bitmap = BitmapFactory.decodeFile(path);
            var drawable = BitmapDrawable(this.getResources(), bitmap);
            mBinding.videoView.setBackground(drawable);
        }
    }

    override fun onUiNotify(name: String, bundle: Bundle) {
        super.onUiNotify(name, bundle)
        when (name) {
            "Advertisement" -> {
                var fileName = bundle.getString("FileName")
                play(fileName)
            }
            "Face" -> {
//                ARouter.getInstance()
//                    .build(ARouterPath.AliveActivity)
//                    .withLong("OrderId", mViewModel.order.id)
//                    .navigation(this, 1000)
            }
            "Payed" -> {
//                deliverDialog = DeliverDialog.newInstance(mViewModel.order)
//                deliverDialog?.show(supportFragmentManager, "DeliverDialog")
            }
            "RefreshVideoViewSize" ->{
                //var isFullScreen = bundle.getBoolean("fullScreen")
                //refreshVideoViewLayout(isFullScreen)
                //play(fileName)
            }
        }
    }

    var clickCount = 0
    var timer: Timer = Timer()
    private lateinit var mPasswordDialog: InputNumberDialog
    fun onClickMaintenance() {
        Log.d("clock",clickCount.toString())
//        this.timer.schedule(8000) { clickCount = 0
//            Log.d("sure",this.toString())
//        }
        if (++clickCount < 5) return
        clickCount = 0
        //this.timer.cancel()
        this.timer.schedule(30 * 1000, {
            if (mPasswordDialog.isShowing) mPasswordDialog.cancel()
            //this.cancel()
        })
        //this.timer.schedule(10 * 1000, { if (mPasswordDialog.isShowing) mPasswordDialog.cancel() })
        var dlg = mPasswordDialog
        dlg.text = ""
        dlg.mInputType = InputType.TYPE_CLASS_NUMBER or InputType.TYPE_NUMBER_VARIATION_PASSWORD
        dlg.setCancelable(false)
        dlg.show()
        dlg.findViewById<View>(R.id.btnConfirm).setOnClickListener {
            if (this.mViewModel.checkPasswordForMaintenance(dlg.text, "2")) dlg.dismiss()
        }
    }

    fun restartAdsTimer(){

    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
     when (event.getAction()) {
//     MotionEvent.ACTION_DOWN->{//0
//         Log.e("TAG", "LinearLayout onTouchEvent 按住");
//         }
//     MotionEvent.ACTION_UP->{//1
//         Log.e("TAG", "LinearLayout onTouchEvent onTouch抬起");
//     }
     MotionEvent.ACTION_MOVE->{//2
         Log.e("TAG", "LinearLayout onTouchEvent 移动");
//         LiveEventBus.get().with("RefreshVideoView").post(false)
//
//         var bundle = Bundle()
//         bundle.putString("UI", "Menus")
//         //String cp = mBinding.videoViewMain.currentPosition
//         LiveEventBus.get().with("SwitchUI").post(bundle)
     }
     }
        return super.onTouchEvent(event)
 }

//    @SuppressLint("SetJavaScriptEnabled")
//    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
//    private fun requestWebView() {
//        /** Layout of webview screen View  */
//        if (internetCheck(mContext)) {
//            mWebView.visibility = View.VISIBLE
//            //layoutNoInternet.visibility = View.GONE
//            mWebView.loadUrl(URL)
//        } else {
////            prgs.visibility = View.GONE
//            mWebView.visibility = View.GONE
////            layoutSplash.visibility = View.GONE
////            layoutNoInternet.visibility = View.VISIBLE
//
//            return
//        }
//        mWebView.isFocusable = true
//        mWebView.isFocusableInTouchMode = true
//        mWebView.settings.javaScriptEnabled = true
//        mWebView.scrollBarStyle = View.SCROLLBARS_INSIDE_OVERLAY
//        mWebView.settings.setRenderPriority(WebSettings.RenderPriority.HIGH)
//        mWebView.settings.cacheMode = WebSettings.LOAD_DEFAULT
//        mWebView.settings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
//
//        mWebView.settings.domStorageEnabled = true
//        mWebView.settings.setAppCacheEnabled(true)
//        mWebView.settings.databaseEnabled = true
//        //mWebView.getSettings().setDatabasePath(
//        //        this.getFilesDir().getPath() + this.getPackageName() + "/databases/");
//
//        // this force use chromeWebClient
//        mWebView.settings.setSupportMultipleWindows(false)
//        mWebView.webViewClient = object : WebViewClient() {
//            override fun shouldOverrideUrlLoading(view: WebView, url: String?): Boolean {
//
//                Log.d(TAG, "URL: " + url!!)
//                if (internetCheck(mContext)) {
//                    //view.loadUrl(url);
//                    // if you wanna open outside of app
//                    if (url != null && url.startsWith(URL)) {
//                        view.loadUrl(url)
//                        return false
//                    }
//                    // Otherwise, give the default behavior (open in browser)
//                    val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
//                    startActivity(intent)
//                    return true
//                } else {
////                    prgs.visibility = View.GONE
//                    mWebView.visibility = View.GONE
////                    layoutSplash.visibility = View.GONE
////                    layoutNoInternet.visibility = View.VISIBLE
//                }
//
//                return true
//            }
//
//            /* @Override
//            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
//                if(internetCheck(mContext)) {
//                    mWebView.setVisibility(View.VISIBLE);
//                    layoutNoInternet.setVisibility(View.GONE);
//                    //view.loadUrl(url);
//                }else{
//                    prgs.setVisibility(View.GONE);
//                    mWebView.setVisibility(View.GONE);
//                    layoutSplash.setVisibility(View.GONE);
//                    layoutNoInternet.setVisibility(View.VISIBLE);
//                }
//                return false;
//            }*/
//
//            override fun onPageStarted(view: WebView, url: String, favicon: Bitmap?) {
//                super.onPageStarted(view, url, favicon)
////                if (prgs.visibility == View.GONE) {
////                    prgs.visibility = View.VISIBLE
////                }
//            }
//
//            override fun onLoadResource(view: WebView, url: String) {
//                super.onLoadResource(view, url)
//            }
//
//            override fun onPageFinished(view: WebView, url: String) {
//                super.onPageFinished(view, url)
////                mLoaded = true
////                if (prgs.visibility == View.VISIBLE)
////                    prgs.visibility = View.GONE
////
////                // check if layoutSplash is still there, get it away!
////                Handler().postDelayed({
////                    layoutSplash.visibility = View.GONE
////                    //viewSplash.getBackground().setAlpha(255);
////                }, 2000)
//            }
//        }
//
//        //file attach request
//        mWebView.webChromeClient = object : WebChromeClient() {
//            override fun onShowFileChooser(
//                webView: WebView, filePathCallback: ValueCallback<Array<Uri>>,
//                fileChooserParams: WebChromeClient.FileChooserParams): Boolean {
////                if (mFilePathCallback != null) {
////                    mFilePathCallback!!.onReceiveValue(null)
////                }
////                mFilePathCallback = filePathCallback
//
//                var takePictureIntent: Intent? = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
//                if (takePictureIntent!!.resolveActivity(this@MainActivity.packageManager) != null) {
//                    // Create the File where the photo should go
////                    var photoFile: File? = null
////                    try {
////                        photoFile = createImageFile()
////                        takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath)
////                    } catch (ex: IOException) {
////                        // Error occurred while creating the File
////                        Log.e(TAG, "Unable to create Image File", ex)
////                    }
////
////                    // Continue only if the File was successfully created
////                    if (photoFile != null) {
////                        mCameraPhotoPath = "file:" + photoFile.absolutePath
////                        takePictureIntent.putExtra(
////                            MediaStore.EXTRA_OUTPUT,
////                            Uri.fromFile(photoFile))
////                    } else {
////                        takePictureIntent = null
////                    }
//                }
//
//                val contentSelectionIntent = Intent(Intent.ACTION_GET_CONTENT)
//                contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE)
//                contentSelectionIntent.type = "image/*"
//
//                val intentArray: Array<Intent?>
//                if (takePictureIntent != null) {
//                    intentArray = arrayOf(takePictureIntent)
//                } else {
//                    intentArray = arrayOfNulls(0)
//                }
//
//                val chooserIntent = Intent(Intent.ACTION_CHOOSER)
//                chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent)
//                chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser")
//                chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray)
//
//                startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE)
//
//                return true
//            }
//        }
//
//    }


    companion object {
        val TAG = "MainActivity"

//        val INPUT_FILE_REQUEST_CODE = 1
//
//        fun internetCheck(context: Context): Boolean {
//            var available = false
//            val connectivity = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
//
//            if (connectivity != null) {
//                val networkInfo = connectivity.allNetworkInfo
//                if (networkInfo != null) {
//                    for (i in networkInfo.indices) {
//                        if (networkInfo[i].state == NetworkInfo.State.CONNECTED) {
//                            available = true
//                            break
//                        }
//                    }
//                }
//            }
//            return available
//        }
    }

}
